package com.android.huimeiqupin.view.recycleview;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
import android.widget.GridView;

import com.android.huimeiqupin.R;

/**
 * Created by Administrator on 2017/8/10.
 */

public class LineGridView extends GridView {
    //定义行数
    private int rownum;
    public LineGridView(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
    }

    public LineGridView(Context context, AttributeSet attrs)
    {
        super(context, attrs);
    }

    public LineGridView(Context context)
    {
        super(context);
    }
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int colnum = getNumColumns(); //获取列数
        int total = getChildCount();  //获取Item总数
        //计算行数
        if (total % colnum == 0) {
            rownum = total / colnum;
        } else {
            rownum = (total / colnum) + 1; //当余数不为0时，要把结果加上1
        }
        Paint localPaint; //设置画笔
        localPaint = new Paint();
        localPaint.setStrokeWidth(2);
        localPaint.setStyle(Paint.Style.STROKE); //画笔实心
        localPaint.setColor(getContext().getResources().getColor(R.color.gray));//画笔颜色

        View view0 = getChildAt(0); //第一个view
        if(view0!=null) {
            int left = view0.getLeft();
            int right = view0.getRight();
            int top = view0.getTop();
            int bottom = view0.getBottom();
            for (int i = 1; i <rownum; i++) {
                //画横线
                canvas.drawLine(left, bottom * i, right * colnum, bottom * i, localPaint);
            }
            for (int c = 1; c < colnum; c++) {
                //画竖线
                canvas.drawLine(right * c, top, right * c, bottom * rownum, localPaint);
            }
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
        super.onMeasure(widthMeasureSpec, expandSpec);
    }
}
